package dhee.wtqshopproject.config;

import dhee.wtqshopproject.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("currentUser");

        // 需要登录的URL检查
        if (user == null && requireAuth(request)) {
            response.sendRedirect("/login.html");
            return false;
        }

        // 防止会话固定攻击
        if (user != null && request.getRequestedSessionId() != null
                && !request.isRequestedSessionIdValid()) {
            session.invalidate();
            response.sendRedirect("/login.html?error=session_expired");
            return false;
        }

        return true;
    }

    private boolean requireAuth(HttpServletRequest request) {
        String uri = request.getRequestURI();
        // 排除登录、注册、静态资源等无需认证的URL
        return !uri.startsWith("/public")
                && !uri.equals("/users/login")
                && !uri.equals("/users/register")
                && !uri.endsWith(".css")
                && !uri.endsWith(".js")
                && !uri.endsWith(".png");
    }
}